#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render
from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import action
from django.http import HttpResponse
from django.conf import settings

from apps.report.models import Report
from apps.report.serializers import ReportSerializers
from utils.rest.views import CustomViewBase
from utils.rest.response import JsonResponse


class ReportPagination(PageNumberPagination):
    """
    测试项目列表自定义分页
    """

    # 默认每页显示的个数
    page_size = 10
    # 可以动态改变每页显示的个数
    page_size_query_param = 'limit'
    # 页码参数
    page_query_param = 'page'
    # 最多能显示多少页
    max_page_size = 100


class ReportViewSet(CustomViewBase):
    """
    测试用例列表

    """
    queryset = Report.objects.all().order_by('-edit_time')
    serializer_class = ReportSerializers
    # 分页
    pagination_class = ReportPagination

    search_fields = ('name',)

    @action(methods=['get'], detail=False)
    def count(self, request):
        count = Report.objects.count()
        return JsonResponse(data={'count': count}, msg='success', code=200)

    @action(methods=['get'], detail=True)
    def download(self, request, pk):
        import os
        path = Report.objects.filter(id=pk)[0].report_path
        file = open(os.path.join(settings.BASE_DIR, 'reports/{}'.format(path)), 'rb')
        response = HttpResponse(file)
        # response['Content-Type'] = 'application/octet-stream'
        response['Content-Type'] = 'text/html'
        response['Content-Disposition'] = 'inline;filename="report.html"'
        return response


